package com.syp.auth.common;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;

import javax.imageio.ImageIO;

/**
 * 图片验证码
 * 
 * @author syp
 * 
 */
public class IVC extends VCGen {

	/**
	 * 使用到Futura字体，系统里没有的话需要安装字体
	 */
	private static final String DEFAULT_FONT = "Futura";// [Algerian,Futura]
	/**
	 * 默认验证码长度
	 */
	private static final int DEFAULT_VC_LEN = 4;
	/**
	 * 默认图片宽度
	 */
	private static final int DEFAULT_IMG_WIDTH = 200;
	/**
	 * 默认图片高度
	 */
	private static final int DEFAULT_IMG_HEIGHT = 80;
	/**
	 * 单例对象
	 */
	private static final IVC instunce = new IVC();

	private IVC() {
	}

	public static IVC getInstunce() {
		return instunce;
	}

	/**
	 * 输出随机验证码图片流,并返回验证码值
	 * 
	 * @param os
	 * @return
	 */
	public String build(OutputStream os) {
		String vc = super.generate(DEFAULT_VC_LEN, ChrLib.FRIEDLY);
		buildImage(DEFAULT_IMG_WIDTH, DEFAULT_IMG_HEIGHT, os, vc);
		return vc;
	}

	/**
	 * 输出随机验证码图片流,并返回验证码值
	 * 
	 * @param os
	 * @return
	 */
	public String build(OutputStream os, int width, int height) {
		String vc = super.generate(DEFAULT_VC_LEN, ChrLib.FRIEDLY);
		buildImage(width, height, os, vc);
		return vc;
	}

	/**
	 * 输出随机验证码图片流,并返回验证码值
	 * 
	 * @param width
	 * @param height
	 * @param os
	 * @param len
	 * @return
	 */
	public String build(OutputStream os, int width, int height, int len) {
		String vc = super.generate(DEFAULT_VC_LEN, ChrLib.FRIEDLY);
		buildImage(width, height, os, vc);
		return vc;
	}

	/**
	 * 输出指定验证码图片流
	 * 
	 * @param width
	 * @param height
	 * @param os
	 * @param vc
	 * @throws IOException
	 */
	public void buildImage(int width, int height, OutputStream os, String vc) {
		int verifySize = vc.length();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Random rand = new Random();
		Graphics2D g2 = image.createGraphics();
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		Color[] colors = new Color[5];
		Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.YELLOW };
		float[] fractions = new float[colors.length];
		for (int i = 0; i < colors.length; i++) {
			colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
			fractions[i] = rand.nextFloat();
		}
		Arrays.sort(fractions);

		g2.setColor(Color.GRAY);// 设置边框色
		g2.fillRect(0, 0, width, height);

		Color c = getRandColor(200, 250);
		g2.setColor(c);// 设置背景色
		g2.fillRect(0, 2, width, height - 4);

		// 绘制干扰线
		Random random = new Random();
		g2.setColor(getRandColor(160, 200));// 设置线条的颜色
		for (int i = 0; i < 20; i++) {
			int x = random.nextInt(width - 1);
			int y = random.nextInt(height - 1);
			int xl = random.nextInt(6) + 1;
			int yl = random.nextInt(12) + 1;
			g2.drawLine(x, y, x + xl + 40, y + yl + 20);
		}

		// 添加噪点
		float yawpRate = 0.05f;// 噪声率
		int area = (int) (yawpRate * width * height);
		for (int i = 0; i < area; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int rgb = getRandomIntColor();
			image.setRGB(x, y, rgb);
		}

		shear(g2, width, height, c);// 使图片扭曲

		g2.setColor(getRandColor(100, 160));
		int fontSize = height - 4;
		Font font = new Font(DEFAULT_FONT, Font.ITALIC, fontSize);
		g2.setFont(font);
		char[] chars = vc.toCharArray();
		for (int i = 0; i < verifySize; i++) {
			AffineTransform affine = new AffineTransform();
			affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (width / verifySize) * i + fontSize / 2, height / 2);
			g2.setTransform(affine);
			g2.drawChars(chars, i, 1, ((width - 10) / verifySize) * i + 5, height / 2 + fontSize / 2 - 10);
		}

		g2.dispose();
		try {
			ImageIO.write(image, "jpg", os);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private Color getRandColor(int fc, int bc) {
		Random rd = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + rd.nextInt(bc - fc);
		int g = fc + rd.nextInt(bc - fc);
		int b = fc + rd.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	private int getRandomIntColor() {
		Random rd = new Random();
		int[] rgb = new int[3];
		for (int i = 0; i < 3; i++) {
			rgb[i] = rd.nextInt(255);
		}
		int color = 0;
		for (int c : rgb) {
			color = color << 8;
			color = color | c;
		}
		return color;
	}

	private void shear(Graphics g, int w1, int h1, Color color) {
		shearX(g, w1, h1, color);
		shearY(g, w1, h1, color);
	}

	private void shearX(Graphics g, int w1, int h1, Color color) {
		Random rd = new Random();
		int period = rd.nextInt(2);

		boolean borderGap = true;
		int frames = 1;
		int phase = rd.nextInt(2);

		for (int i = 0; i < h1; i++) {
			double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
			g.copyArea(0, i, w1, 1, (int) d, 0);
			if (borderGap) {
				g.setColor(color);
				g.drawLine((int) d, i, 0, i);
				g.drawLine((int) d + w1, i, w1, i);
			}
		}

	}

	private void shearY(Graphics g, int w1, int h1, Color color) {
		Random rd = new Random();
		int period = rd.nextInt(40) + 10; // 50;

		boolean borderGap = true;
		int frames = 20;
		int phase = 7;
		for (int i = 0; i < w1; i++) {
			double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
			g.copyArea(i, 0, 1, h1, 0, (int) d);
			if (borderGap) {
				g.setColor(color);
				g.drawLine(i, (int) d, i, 0);
				g.drawLine(i, (int) d + h1, i, h1);
			}

		}

	}
}
